package com.cat.mrli.rat.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;
import android.util.Log;

import static android.opengl.GLES20.*;

/**
 * Created by MrLi on 2017/6/25.
 */

public final class  TextureHelper {
    public static final String TAG = "TextureHelper";

    public static int loadTexture(Context context,int resourceId){
        final int[] textureObjectIds = new int[1];
        glGenTextures(1,textureObjectIds,0);
        if (0 == textureObjectIds[0]){
            if (LoggerConfig.ON){
                Log.w(TAG,"无法生成纹理对象");
            }
            return 0;
        }
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = false;
        final Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),resourceId,options);
        if (null == bitmap){
            if (LoggerConfig.ON){
                Log.w(TAG,"位图载入失败");
            }
            glDeleteTextures(1,textureObjectIds,0);
            return 0;
        }
        glBindTexture(GL_TEXTURE_2D,textureObjectIds[0]);
        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);
        glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
        GLUtils.texImage2D(GL_TEXTURE_2D,0,bitmap,0);
        bitmap.recycle();
        glGenerateMipmap(GL_TEXTURE_2D);
        glBindTexture(GL_TEXTURE_2D,0);
        return textureObjectIds[0];
    }

}
